# -*- coding: utf-8 -*-
# @Time    : 2021/2/18 16:38
# @Author  : jcl
# @Email   : 2195932461@qq.com
# @File    : manager.py
# @Software: PyCharm
from PyQt5.QtCore import pyqtSlot
from PySide2.QtCore import Qt
from PySide2.QtGui import QFont

from pyminer2.extensions.extensions_store.ui import window
from PySide2.QtWidgets import QDialog, QApplication, QListWidgetItem, QPushButton, QWidget, QHBoxLayout, QLabel, \
    QVBoxLayout, QComboBox
from PySide2 import QtGui
from PySide2 import QtCore
import requests
import urllib.request


class StoreItemWidget(QWidget):
    def __init__(self, data):
        super().__init__()
        name = data['name']
        icon = data['icon']
        star = data['star']
        download = data['download']
        tag = data['tag']

        # 总体横向布局
        layout_main = QHBoxLayout()
        icon_label = QLabel()  # 头像显示
        icon_label.setFixedSize(40, 40)
        maps = QtGui.QPixmap()
        maps.loadFromData(icon)
        icon_label.setPixmap(maps)
        icon_label.setScaledContents(True)
        layout_right = QHBoxLayout()
        layout_v = QVBoxLayout()
        name_label = QLabel()
        layout_right.addWidget(name_label)
        install = QPushButton('install')
        install.setFixedWidth(70)
        install.setFixedHeight(21)
        install.setStyleSheet("""
        color:green;
        background-color:white;
        border: 1px solid green;
        border-radius: 2px;
        padding: 1px 4px;
        """)
        layout_right.addWidget(install)
        name_label.setText(name)
        name_label.setFont(QFont("Courier new", 11, QFont.Bold))
        layout_main.addWidget(icon_label)

        layout_v.addLayout(layout_right)
        tip_label = QLabel('📥{0} ⭐{1} 📚{2}'.format(download, star, tag))
        tip_label.setFont(QFont("Microsoft YaHei", 9, QFont.Normal))
        tip_label.setStyleSheet("""
        color:rgb(100,100,100,100);
        """)
        layout_v.addWidget(tip_label)

        layout_main.addLayout(layout_v)
        self.keywords = name+tag
        self.setLayout(layout_main)


class StoreItemDetailWidget(QWidget):
    """展示图标，名称，作者，已安装版本号，最新版本号，升级，卸载，重新安装，启动，停用功能管理"""

    def __init__(self, data):
        super().__init__()
        self.icon_label = QLabel()
        self.icon_label.setFixedSize(60, 60)
        self.icon_label.setScaledContents(True)
        self.name_label = QLabel()
        self.name_label.setFont(QFont("Courier new", 15, QFont.Bold))
        self.author_label = QLabel()
        self.version_label = QLabel()
        self.version_label.setStyleSheet("""
        color:rgb(150,150,150,200);
        """)
        self.combox = QComboBox()
        self.combox.setFixedSize(80, 30)
        self.set_value(data)
        h_layout = QHBoxLayout()
        v_layout = QVBoxLayout()
        h_layout.addWidget(self.icon_label)
        v_layout.addWidget(self.name_label)
        v_layout.addWidget(self.author_label)
        v_layout.addWidget(self.version_label)
        h_layout.addLayout(v_layout)
        h_layout.addWidget(self.combox)
        self.setLayout(h_layout)

    def set_value(self, data):
        name = data['name']
        icon = data['icon']
        author = data['author']
        current_version = data['current_version']
        latest_version = data['latest_version']
        status = data['status']
        index_url = data['index_url']
        maps = QtGui.QPixmap()
        maps.loadFromData(icon)
        self.icon_label.setPixmap(maps)
        self.icon_label.setScaledContents(True)
        self.name_label.setText(name)
        self.author_label.setText("<style> a {text-decoration: none} </style><A href='%s'>%s</a>" % (index_url, author))
        if not current_version or current_version == latest_version:
            self.version_label.setText(latest_version)
            choices = ['Reinstall', 'Uninstall']
        else:
            self.version_label.setText("{0} (latest:{1})".format(current_version, latest_version))
            choices = ['Update', 'reinstall', 'uninstall']
        if status:  # 检测当前插件是否启用
            choices.append('Disable')
        else:
            choices.append('Enable')
        self.combox.clear()
        self.combox.addItems(choices)


class StoreManager(window.Ui_Dialog):
    def __init__(self):
        self.dialog = QDialog()
        self.setupUi(self.dialog)
        self.data = []
        self.host = 'http://www.pyminer.com'
        self.get_extension_list()
        self.generate_items()
        window_flag = Qt.Dialog
        window_flag |= Qt.WindowMinimizeButtonHint
        window_flag |= Qt.WindowMaximizeButtonHint
        window_flag |= Qt.WindowCloseButtonHint
        self.dialog.setWindowFlags(window_flag)
        self.listWidget.itemClicked.connect(self.listwidgetclicked)
        self.search_lineEdit.textChanged.connect(self.on_textChanged)
        self.dialog.exec_()

    def listwidgetclicked(self, item: QListWidgetItem):
        self.detail_widget.set_value(item.detail)

    def get_extension_list(self):
        r = requests.get(self.host + '/api/v1/plugin/')
        if r.status_code == 200:
            self.data = r.json()

    def generate_items(self):
        for item_data in self.data:
            name = item_data['name']
            item_data['star'] = self.get_star(name)
            item_data['tag'] = self.get_tag(name)
            item_data['download'] = item_data['views']
            item_data['author'] = item_data['author']['username']
            item_data['current_version'] = '1.0.0'
            item_data['latest_version'] = '1.0.1'
            item_data['status'] = True
            icon = urllib.request.urlopen(item_data['icon_url']).read()
            item_data['icon'] = icon
            item = QListWidgetItem()
            item.setSizeHint(QtCore.QSize(180, 70))
            item.detail = item_data
            self.listWidget.addItem(item)
            self.listWidget.setItemWidget(item, StoreItemWidget(item_data))
            if self.verticalLayout_detail.count() == 1:
                self.detail_widget = StoreItemDetailWidget(item.detail)
                self.verticalLayout_detail.insertWidget(0, self.detail_widget)

    def get_tag(self, name):
        """返回插件标签"""
        data = []
        tags = []
        r = requests.get(self.host + '/api/v1/plugin_tag/{}/'.format(name))
        if r.status_code == 200:
            data = r.json()
        for item in data:
            tags.append(item['name'])
        return ','.join(tags)

    def get_star(self, name):
        """返回点赞数"""
        r = requests.get(self.host + '/api/v1/plugin_star/{}/'.format(name))
        if r.status_code == 200:
            return r.json()['star_num']
        else:
            return 0

    @pyqtSlot(str)
    def on_textChanged(self, text):
        """实现查找功能"""
        for row in range(self.listWidget.count()):
            it = self.listWidget.item(row)
            widget = self.listWidget.itemWidget(it)
            if text:
                it.setHidden(not self.filter(text, widget.keywords))
            else:
                it.setHidden(False)

    def filter(self, text, keywords):
        return text in keywords


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    StoreManager()
